<template>
  <div class="app-container">
    <!-- 一、查询条件框 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="章节名称" prop="chapterName">
        <el-input
          v-model="queryParams.chapterName"
          placeholder="请输入章节名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="解析字段" prop="analysisField">
        <el-input
          v-model="queryParams.analysisField"
          placeholder="请输入解析字段"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
    </el-form>

    <!-- 二、用户导入框 -->
    <div class="uploadDiv" style="display: flex;flex-direction: column;align-items: center;min-height: 100vh;">
      <el-upload
        ref="upload"
        :limit="10"
        multiple
        accept=".pdf"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入pdf格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer" style="margin-top: 20px;">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
<!--        <el-button @click="upload.open = false">清 空</el-button>-->
      </div>
    </div>
  </div>
</template>

<script>
import {getToken} from "@/utils/auth";
import axios from 'axios'

export default {
  name: "Analysis",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/tools/analysis/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        chapterName: undefined,
        analysisField: undefined,
      },
      // 列信息
      columns: [
        {key: 0, label: `用户编号`, visible: true},
        {key: 1, label: `用户名称`, visible: true},
        {key: 2, label: `用户昵称`, visible: true},
        {key: 3, label: `部门`, visible: true},
        {key: 4, label: `手机号码`, visible: true},
        {key: 5, label: `状态`, visible: true},
        {key: 6, label: `创建时间`, visible: true}
      ],
      // 表单校验
      rules: {
        userName: [
          {required: true, message: "用户名称不能为空", trigger: "blur"},
          {min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        nickName: [
          {required: true, message: "用户昵称不能为空", trigger: "blur"}
        ],
        password: [
          {required: true, message: "用户密码不能为空", trigger: "blur"},
          {min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur'}
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    handleQuery() {
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
    },
    // 提交上传文件
    // submitFileForm() {
    //   this.$refs.upload.submit();
    // }
    submitFileForm() {

      if (this.$refs.upload.uploadFiles.length === 0) {
        this.$message.warning('请选择要上传的文件');
        return;
      }

      const formData = new FormData();

      // 添加章节名称和解析字段
      formData.append('chapterName', this.queryParams.chapterName);
      formData.append('analysisField', this.queryParams.analysisField);

      // 假设您已经通过el-upload组件选择了多个文件
      this.$refs.upload.uploadFiles.forEach(file => {
        formData.append('files', file.raw); // 'files[]' 应该与服务器端期望的参数名相匹配
      });

      // 发送 formData 到服务器
      fetch(this.upload.url, {
        method: 'POST',
        headers: { ...this.upload.headers },
        body: formData,
      })
        .then(response => {
          if (!response.ok) throw new Error('Network error');
          return response.blob(); // 关键：将响应转为Blob对象
        })
        .then(blob => {
          // 创建临时下载链接
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = 'dsxw.xlsx'; // 文件名需与后端设置的保持一致
          a.style.display = 'none';
          document.body.appendChild(a);
          a.click(); // 触发下载
          document.body.removeChild(a);
          this.$refs.upload.clearFiles();
          window.URL.revokeObjectURL(url); // 释放内存
        })
        .catch(error => {
          // 错误处理逻辑
        });

    }
  }
};
</script>
